cmake_minimum_required(VERSION 3.12)

set(CMAKE_CXX_STANDARD 20)

project(main)

if (MSVC)
    add_compile_options(/Zc:preprocessor /utf-8 /DNOMINMAX /D_USE_MATH_DEFINES /EHsc /bigobj)
else()
    if (WIN32)
        add_compile_options(-finput-charset=utf-8 -fexec-charset=utf-8)
    endif()
    add_compile_options(-Wall -Wextra -Werror=return-type)
endif()


set(libraries Boost::locale fmt)


# find_package(fmt REQUIRED)
# find_package(Boost REQUIRED COMPONENTS locale)
foreach(lib_name IN LISTS libraries)
string(FIND "${lib_name}" "::" found)
    if (found EQUAL -1)
        find_package(${lib_name} REQUIRED)
    else()
        # split by ::
        string(REGEX REPLACE "::" ";" lib_name_list "${lib_name}")
        list(GET lib_name_list 0 lib_name)
        list(GET lib_name_list 1 lib_name_component)
        find_package(${lib_name} REQUIRED COMPONENTS ${lib_name_component})
    endif()
endforeach()

file(GLOB sources CONFIGURE_DEPENDS "examples/*.cpp")
foreach(source IN LISTS sources)
    get_filename_component(name ${source} NAME_WE)
    add_executable(${name} ${source})
    # read file content and check if it really required "boost/*" include
    foreach(lib_name IN LISTS libraries)
        string(TOLOWER "${lib_name}" lib_expr)
        string(FIND "${lib_expr}" "::" found)
        if (found EQUAL -1)
            string(APPEND lib_name "::${lib_name}")
            string(APPEND lib_expr "/")
        else()
            string(REPLACE "::" "/" lib_expr "${lib_expr}")
        endif()
        file(STRINGS ${source} lines REGEX "#include[ \t]+[\"<]${lib_expr}.*[\">]")
        if (lines)
            target_link_libraries(${name} PRIVATE ${lib_name})
        endif()
    endforeach()
    target_link_libraries(${name} PRIVATE fmt::fmt Boost::locale)
    target_include_directories(${name} PRIVATE include)
endforeach()

# file(GLOB subdirs CONFIGURE_DEPENDS "examples/*/CMakeLists.txt")
# foreach(subdir IN LISTS subdirs)
#     get_filename_component(name ${subdir} DIRECTORY)
#     get_filename_component(name ${name} NAME)
#     add_subdirectory(${name})
# endforeach()
